package com.qf.zyh.web.filter;

import com.qf.zyh.common.Const;
import com.qf.zyh.entity.User;
import com.qf.zyh.services.Impl.UerServicesImpl;
import com.qf.zyh.services.UserServices;
import com.qf.zyh.util.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter(filterName = "Filter02",value = "/login.jsp")
public class Filter02 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //首先获取cookie，然后遍历cookie的数据，解码之后根据：拆分用户名和密码，然后登录，登录成功转发到首页
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie :cookies){
            //找出所有cookie中和自身存储的值相同的cook
            if (cookie.getName().equals(Const.UserCont.AUTO_LOGIN)) {
                //找到相同的则通过value获取数据
                String value = cookie.getValue();
                //将数据解码
                String decode = Base64Utils.decode(value);
                //从0下标开始，截止到：位置
                String username = decode.substring(0, decode.indexOf(":"));
                //单个参数为从改位置下标开始到后面所有，从冒号后开始截取，则：下标+1
                String password = decode.substring(decode.indexOf(":") + 1);
                UserServices us = new UerServicesImpl();
                User login = us.login(username, password);
                if (login!=null) {
                    request.getSession().setAttribute(Const.UserCont.IS_LOGIN,login);
                    response.sendRedirect(request.getContextPath()+"/index.jsp");
                    return;
                }

            }
        }
            filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
